package com.mi.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSON;
import com.mi.bean.CustomersBean;
import com.mi.service.impl.LoginServiceImpl;
import com.mi.utils.MyUtils;

/**
 * Servlet implementation class LoginAction
 */
@WebServlet("/CustomerLoginAction")
public class CustomerLoginAction extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * 对用户登录页面发过来的请求数据进行处理
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 取出客户端发送的表单数据
		// 调用方法获取映射表单数据的实体类的实例
		CustomersBean customerB = MyUtils.convertFormData2Bean(request, CustomersBean.class);
		/*System.out.println("loadingAction-表单上传结果"+customerB.toString());*/
		// 调用model层进行业务逻辑处理（查询数据库进行用户信息验证）
		List<CustomersBean> lstCustomers = MyUtils.getInstance(LoginServiceImpl.class).queryLoginInfo(customerB);
		
		/*System.out.println("loadingAction-数据库查询结果"+lstCustomers.toString());*/
		// 根据 接收到的model层的返回结果 进行用户视图的转发控制

		if (lstCustomers != null && lstCustomers.size() > 0) {
			// 登陆成功，跳转到登陆成功页面
			
			// 获取用户的所有信息，存到会话中
			String strId = lstCustomers.get(0).getCustomer_id();
			String strName = lstCustomers.get(0).getCustomer_name();
			String strTel = lstCustomers.get(0).getCustomer_tel();
			String strEmail = lstCustomers.get(0).getCustomer_email();
			String strImg = lstCustomers.get(0).getCustomer_img();
			
			// 将用户名存储到session中
			request.getSession().setAttribute("sid", strId);
			request.getSession().setAttribute("sname", strName); //session设值	
			request.getSession().setAttribute("stel", strTel);   //session设值	
			request.getSession().setAttribute("semail", strEmail);
			request.getSession().setAttribute("simg", strImg);
			
			// 安全目录下要使用转发来跳转页面
			request.getRequestDispatcher("index.jsp").forward(request, response);
		} else {
			// 登录失败，转发到登录页重新登录
			request.getRequestDispatcher("loading.jsp").forward(request, response);
		}
	}

}
